package middleware

import (
	"net/http"

	"github.com/gin-gonic/gin"
	oauth2server "github.com/go-oauth2/oauth2/v4/server"
)

// OAuth2TokenVerify 从 Authorization header 中验证 token，验证成功后注入 context
func OAuth2TokenVerify(oauthServer *oauth2server.Server) gin.HandlerFunc {
	return func(c *gin.Context) {
		if oauthServer == nil {
			c.JSON(http.StatusInternalServerError, gin.H{"error": "oauth server not initialized"})
			c.Abort()
			return
		}
		ti, err := oauthServer.ValidationBearerToken(c.Request)
		if err != nil {
			c.JSON(http.StatusUnauthorized, gin.H{"error": "invalid token", "detail": err.Error()})
			c.Abort()
			return
		}
		// 将 token info 与 user id 放入上下文
		c.Set("tokenInfo", ti)
		c.Set("userID", ti.GetUserID())
		c.Next()
	}
}